package com.house.rent.ui.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import androidx.annotation.NonNull;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.base.lib.mvp.present.BasePresenter;
import com.base.lib.ui.dialog.SelectMenuDialog;
import com.base.lib.util.MaterialDialogUtils;
import com.house.rent.R;
import com.house.rent.entity.UserEntity;
import com.house.rent.util.BASE64Utils;
import com.house.rent.util.ViewUtils;

import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class IdCardDetailActivity extends BaseActivity {
    private static final int CAMERA_REQUEST = 0x111;
    private static final int PICK_REQUEST = 0x222;


    @BindView(R.id.iv_id_card1)
    ImageView mIvIdCard1;
    @BindView(R.id.iv_id_card2)
    ImageView mIvIdCard2;
    @BindView(R.id.btn_id_card_audit)
    Button mBtnIdCard;

    @BindView(R.id.btn_id_card1)
    Button mBtn1;
    @BindView(R.id.btn_id_card2)
    Button mBtn2;

    private int mUserId;
    private UserEntity mEntity;
    /**
     * 是否为审核
     */
    private boolean mAudit;
    /**
     * 点击上传图片位置
     */
    private int mClickPosition;
    private Uri imageUri;

    public static void start(Context context, int userId) {
        start(context, userId, false);
    }

    public static void start(Context context, int userId, boolean audit) {
        Intent starter = new Intent(context, IdCardDetailActivity.class);
        starter.putExtra("userId", userId);
        starter.putExtra("audit", audit);
        context.startActivity(starter);
    }

    @Override
    public void initIntent(Intent intent) {
        super.initIntent(intent);
        mUserId = intent.getIntExtra("userId", 0);
        mAudit = intent.getBooleanExtra("audit", false);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_id_card;
    }

    @Override
    protected void initTop() {
        if (mAudit) {
            setTitle("身份证审核");
        } else {
            setTitle("身份证信息");
            enableRight("保存", v -> {
                if (imageUri != null) {
                    doSaveRequest();
                } else {
                    finish();
                }
            });
        }
    }

    @Override
    protected void initView(Bundle savedInstanceState) {

    }

    private void initView() {
        if (mAudit) {
            mIvIdCard1.setLongClickable(false);
            mIvIdCard2.setLongClickable(false);
            mBtnIdCard.setText("审核");
            mBtnIdCard.setVisibility(View.VISIBLE);
            mBtn1.setVisibility(View.GONE);
            mBtn2.setVisibility(View.GONE);
        } else {
            mIvIdCard1.setLongClickable(true);
            mIvIdCard2.setLongClickable(true);
            mBtnIdCard.setVisibility(View.GONE);
            mBtn1.setVisibility(View.VISIBLE);
            mBtn2.setVisibility(View.VISIBLE);
        }

        //身份证:用子线程加载
        loadIdCardImage();

        if (mEntity.isAudit()) {
            mBtnIdCard.setText("已审核通过");
        } else {
            mBtnIdCard.setText("审核");
        }
    }

    @SuppressLint("StaticFieldLeak")
    private void loadIdCardImage() {
        List<Bitmap> bitmaps = new ArrayList<>();
        new AsyncTask<Void, Void, Void>() {

            @Override
            protected Void doInBackground(Void... voids) {
                String idCardPhotoFront = mEntity.getIdCardPhotoFront();
                if (!TextUtils.isEmpty(idCardPhotoFront)) {
                    bitmaps.add(BASE64Utils.string2Bitmap(idCardPhotoFront));

                }
                String idCardPhotoBack = mEntity.getIdCardPhotoBack();
                if (!TextUtils.isEmpty(idCardPhotoBack)) {
                    bitmaps.add(BASE64Utils.string2Bitmap(idCardPhotoBack));
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                if (bitmaps.size() > 0) {
                    mIvIdCard1.setImageBitmap(bitmaps.get(0));
                    mIvIdCard2.setImageBitmap(bitmaps.get(1));
                }
            }
        }.execute();
    }

    @Override
    protected void initListeners() {
        mIvIdCard1.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                MaterialDialogUtils.show(mContext, "是否删除？",
                        (dialog, which) -> {
                            mEntity.setIdCardPhotoFront("");
                            mIvIdCard1.setImageResource(R.mipmap.ic_place);
                        });
                return true;
            }
        });
        mIvIdCard2.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                MaterialDialogUtils.show(mContext, "是否删除？",
                        (dialog, which) -> {
                            mEntity.setIdCardPhotoBack("");
                            mIvIdCard2.setImageResource(R.mipmap.ic_place);
                        });
                return true;
            }
        });
    }

    @Override
    protected BasePresenter initPresenter() {
        return null;
    }

    @Override
    protected void initData() {
        //请求用户信息
        addParams("userId", mUserId);
        sendRequest("user/userInfo", UserEntity.class);
    }

    @OnClick({R.id.btn_id_card1, R.id.btn_id_card2, R.id.btn_id_card_audit})
    public void onViewClick(View view) {
        switch (view.getId()) {
            case R.id.btn_id_card1:
                mClickPosition = 0;
                showSelectPicDialog();
                break;
            case R.id.btn_id_card2:
                mClickPosition = 1;
                showSelectPicDialog();
                break;
            case R.id.btn_id_card_audit:
                if (mEntity.isAudit()) {
                    showMessage("该身份信息已审核通过");
                    return;
                }
                showAuditDialog();
                break;
            default:
                break;
        }
    }

    private void showAuditDialog() {
        MaterialDialogUtils.show(mContext, "审核结果？", "不通过", new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                requestCheck(false);
            }
        }, "通过", new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                requestCheck(true);
            }
        });
    }


    private void requestCheck(boolean audit) {
        showLoading("正在处理...");
        addParams("userId", mEntity.getId());
        addParams("audit", audit);
        sendRequest("user/audit", UserEntity.class);
    }

    @Override
    protected void onRequestSuccess(String reqId, Object obj) {
        super.onRequestSuccess(reqId, obj);
        switch (reqId) {
            case "user/userInfo":
                if (obj instanceof UserEntity) {
                    mEntity = (UserEntity) obj;
                    initView();
                }
                break;
            case "user/audit":
                showMessage("审核通过");
                finish();
                break;
            case "user/updateInfo":
                showMessage("保存成功");
                finish();
                break;
            default:
                break;
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            Bitmap bitmap = null;
            switch (requestCode) {
                case CAMERA_REQUEST:
                    try {
                        bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                    break;
                case PICK_REQUEST:
                    imageUri = data.getData();
                    String imagePath = ViewUtils.getAbsolutePath(this, imageUri);
                    bitmap = BitmapFactory.decodeFile(imagePath);
                    break;
                default:
                    break;
            }
            if (bitmap != null) {
                String bitmapStr = BASE64Utils.bitmap2String(bitmap);
                if (mClickPosition == 0) {
                    mIvIdCard1.setImageBitmap(bitmap);
                    mEntity.setIdCardPhotoFront(bitmapStr);
                } else {
                    mIvIdCard2.setImageBitmap(bitmap);
                    mEntity.setIdCardPhotoBack(bitmapStr);
                }
            }
        }
    }

    private void showSelectPicDialog() {
        SelectMenuDialog menuDialog = new SelectMenuDialog(mContext);
        menuDialog.setMenu(new String[]{"选择相册", "相机"}, (dialog, item, position) -> {
            dialog.dismiss();
            switch (position) {
                case 0:
                    ViewUtils.openGallery(this, PICK_REQUEST);
                    break;
                default:
                    imageUri = ViewUtils.openCamera(this, CAMERA_REQUEST);
                    break;
            }
        });
        menuDialog.show();
    }

    private void doSaveRequest() {
        addParams("userId", mEntity.getId());
        addParams("mobile", mEntity.getMobile());
        addParams("nickName", mEntity.getNickName());
        addParams("idCardPhotoFront", mEntity.getIdCardPhotoFront());
        addParams("idCardPhotoBack", mEntity.getIdCardPhotoBack());

        sendRequest("user/updateInfo", null);
    }
}
